package com.victor9ac.ip.finder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Component;

/**
 * Use hostip info free usage rest version based on MaxMind
 * 
 * @author victor9ac
 *
 */
@Component
public class IpFinder {

	public static final String UNSUCESSFUL_LOCATION_IP = "UNKNOWN";
	private static final String PREFIX_NOT_LOCATED = "(";
	private static final String HOST_IP_INFO_ENDPOINT = "http://api.hostip.info/get_html.php?ip=";
	private static final String CITY_TAG = "City: ";
	private static final String IP_TAG = "IP: ";

	/**
	 * 
	 * 
	 * 
	 * @param ip
	 * @return cityLocation name, if not found, @return UNSUCESSFUL_LOCATION_IP
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String getLocationFromIp(String ip) throws URISyntaxException,
			ClientProtocolException, IOException {

		HttpClientBuilder create = HttpClientBuilder.create();
		HttpClient client = create.build();

		URI uri = new URI(HOST_IP_INFO_ENDPOINT + ip);

		System.out.println(uri);
		HttpGet request = new HttpGet(uri);
		HttpResponse response = client.execute(request);

		StringBuilder strBuilder = inputStreamToString(response.getEntity()
				.getContent());

		String bodyStringResponse = strBuilder.toString();

		String cityLocated = getCityName(bodyStringResponse);

		cityLocated = validateCityName(cityLocated);

		return cityLocated;

	}

	private String validateCityName(String cityLocated) {
		if (cityLocated != null && cityLocated.startsWith(PREFIX_NOT_LOCATED)) {
			cityLocated = UNSUCESSFUL_LOCATION_IP;
		}
		return cityLocated;
	}

	private String getCityName(String bodyStringResponse) {
		String cityLocated = bodyStringResponse.substring(
				bodyStringResponse.indexOf(CITY_TAG) + CITY_TAG.length(),
				bodyStringResponse.indexOf(IP_TAG));
		return cityLocated;
	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}
		return total;
	}

}
